﻿using MaterialTypeRecognition.Shell.SaveInfos;
using MaterialTypeRecognition.Shell.SaveInfoService;
using MaterialTypeRecognition.Shell.Utils;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Input;

namespace MaterialTypeRecognition.Shell
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly IServiceProvider _services;

        private readonly StopwatchTimer _timer;

        private readonly string _iconFile;

        public MainWindow(IServiceProvider services, StopwatchTimer timeUpTimer)
        {
            _iconFile= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Application.ico"); 

            if(!File.Exists(_iconFile))
            {
                throw new FileNotFoundException(_iconFile);
            }

            _services = services;
            _timer = timeUpTimer;
            this.Loaded += MainWindow_Loaded;
            InitializeComponent();
        }

        private int _rfidInterval;

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            WindowNotifyIcon.AttachToWindow(this, new System.Drawing.Icon(_iconFile));
            var service = _services.GetRequiredService<ISaveInfoService>();
            var saveInfo = service.Read<AppSettingSaveInfo>();
            _rfidInterval = saveInfo.RfidInterval!.Value;

            this.PasswordBox.KeyUp += PasswordBox_KeyUp;
            this.PasswordBox.KeyDown += PasswordBox_KeyDown;
        }

        private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 回车结束输入。
                _timer.Reset();

                this.AuthenButton.Command?.Execute(this.PasswordBox);
                this.PasswordBox.Password = string.Empty;
            }
            else
            {
                // 开始计时。
                _timer.Start(TimeSpan.FromMilliseconds(_rfidInterval));
            }
        }

        private void PasswordBox_KeyUp(object sender, KeyEventArgs e)
        {
            _timer.Stop();

            if (_timer.IsTimeUp)
            {
                this.PasswordBox.Password = string.Empty;
            }
        }
    }
}
